# koroFileHeader at Home PC
# Create: 2021-04-10 10:36:06
# LastEdit: 2021-04-11 10:17:19
"""根据官方示例调试
快速入门：使用 Python 运行你的第一个 Resource Graph 查询
https://docs.microsoft.com/zh-cn/azure/governance/resource-graph/first-query-python
多云：使用用于 Python 的 Azure 库连接到所有区域
https://docs.microsoft.com/zh-cn/azure/developer/python/azure-sdk-sovereign-domain
"""
__author__ = '749B'

import os, sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 
sys.path.append(BASE_DIR)

# Import Azure Resource Graph library
import azure.mgmt.resourcegraph as arg

# 认证
from msrestazure.azure_cloud import AZURE_CHINA_CLOUD as CLOUD
from azure.mgmt.resource import SubscriptionClient
#from azure.mgmt.resourcegraph import ResourceGraphClient
# pylint: disable = import-error
from learning.source_code_modify.my_resource_graph_client import MyResourceGraphClient as ResourceGraphClient
from azure.identity import DefaultAzureCredential

# 加载环境变量
from environs import Env
env = Env()
env.read_env()

# When using sovereign domains (that is, any cloud other than AZURE_PUBLIC_CLOUD),
# you must use an authority with DefaultAzureCredential.
credential = DefaultAzureCredential(authority=CLOUD.endpoints.active_directory)

subscription_client = SubscriptionClient(
    credential,
    base_url=CLOUD.endpoints.resource_manager,
    credential_scopes=[CLOUD.endpoints.resource_manager + "/.default"])

resource_graph_client = ResourceGraphClient(
    credential,
    base_url=CLOUD.endpoints.resource_manager,
    credential_scopes=[CLOUD.endpoints.resource_manager + "/.default"])

# Get your credentials from Azure CLI (development only!) and get your subscription list
subsRaw = []
for sub in subscription_client.subscriptions.list():
    subsRaw.append(sub.as_dict())
subsList = []
for sub in subsRaw:
    subsList.append(sub.get('subscription_id'))

# Create Azure Resource Graph client and set options
argQueryOptions = arg.models.QueryRequestOptions(result_format="table")  # "table" or "objectArray"

# Create query
strQuery = "Resources | project name, type | limit 5"
argQuery = arg.models.QueryRequest(subscriptions=subsList, query=strQuery, options=argQueryOptions)

# Run query
argResults = resource_graph_client.resources(argQuery)

# Show Python object
print(type(argResults.data))
print(argResults.data)

columns = [i.get('name') for i in argResults.data.get('columns')]
print(columns)
for row in argResults.data.get('rows'):
    line = [i for i in row]
    print(line)

